﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace jumping_on_blocks
{
    class ManlyModel
    {
        //The model that gives meaning to this Manly Model
        private Model m_model;
        private Texture2D[] m_textures;

        public Model model
        {
            get { return m_model; }
        }

        public Texture2D[] textures
        {
            get { return m_textures; }
        }

        public ManlyModel(Model inputModel, Effect superEffective)
        {
            int textureCount = 0;
            foreach (ModelMesh mesh in inputModel.Meshes)
                textureCount += mesh.Effects.Count;
            m_textures = new Texture2D[textureCount];
            int i = 0;
            foreach (ModelMesh mesh in inputModel.Meshes)
                foreach (BasicEffect currentEffect in mesh.Effects)
                    m_textures[i++] = currentEffect.Texture;

            foreach (ModelMesh mesh in inputModel.Meshes)
                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                    meshPart.Effect = superEffective.Clone();

            m_model = inputModel;
        }

        public void Draw(Camera camera, Matrix worldMatrix, string technique)
        {
            Matrix[] modelTransforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(modelTransforms);
            int i = 0;
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (Effect currentEffect in mesh.Effects)
                {
                    //Commented line below is unnecessary because it uses the coordinates of a vertex with respect to our mesh's center,
                    //and transforms it with the world matrix. This transformation is already done in the effects file.
                    //Matrix wMatrix = modelTransforms[mesh.ParentBone.Index] * worldMatrix;
                    currentEffect.CurrentTechnique = currentEffect.Techniques[technique];
                    currentEffect.Parameters["xWorldViewProjection"].SetValue(worldMatrix * camera.viewMatrix * camera.projectionMatrix);
                    currentEffect.Parameters["xWorld"].SetValue(worldMatrix);
                    currentEffect.Parameters["xColor"].SetValue(new Vector4(1.0f, 1.0f, 1.0f, 1.0f));
                    currentEffect.Parameters["xLightPos"].SetValue(new Vector3(2.0f, 20.0f, -2.0f));
                    currentEffect.Parameters["xTexture"].SetValue(textures[i++]);
                    currentEffect.Parameters["xCameraAngle"].SetValue(Vector3.Transform(Vector3.Forward, camera.rotation));
                    currentEffect.Parameters["xCameraPos"].SetValue(camera.position);
                }
                mesh.Draw();
            }
        }
    }
}
